<?php

// +----------------------------------------------------------------------
// | 用于定时处理优惠券个数已经十分到期时间
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://aitaoker.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Caption 1674653@qq.com
// +----------------------------------------------------------------------

$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
$itkconfig = unserialize($api_config);

vendor('Itaoke.TopClient');
vendor('Itaoke.RequestCheckUtil');
vendor('Itaoke.Logger');
$top = new \TopClient;
$top->appkey = $itkconfig['app_key'];
$top->secretKey = $itkconfig['app_secret'];
$req = $top->load_api('ItaokeItemUpdateRequest');


$item = M('Items');
$where['coupon_end_time']= array('EGT',time());						//只批量处理时间正常的优惠券
$where['status'] ='underway';										//优惠券
if(C('itk_refresh_open') == 0){
	$where['isq']=1;
}
$perCount = C('itk_plan_pernum');													//最大更新个数 即定时刷新机制一次性最大刷新多少个
$start_pos = F('refresh_count') != '' ? F('refresh_count'):0;		//记录首次刷新的条数
$end_pos = $start_pos+$perCount;
$j=0;																//记录循环次数 若不足500 则代表更新结束(清空缓存)
$res = $item->where($where)->order("id asc")->limit($start_pos.','. $end_pos )->select();

for($i=0;$i<count($res);$i++)
{
	$j++;
	$req->putOtherTextParam('num_iid',$res[$i]['num_iid']);				// 设置商品ID
	$req->putOtherTextParam('quanurl',$res[$i]['quanurl']);				// 设置quanurl
	$resp = (array)$top->execute($req);

	if($resp['status'] != '0000')
	{
		break;
	}else{
		$_res=$resp['data'];

		if( $res[$i]['isq']!=1){		// 无券
			unset($_res['quan_receive']);
			unset($_res['quan_surplus']);
		}else{
			if($_res['quan_surplus']==0){		// 过期
				$_res['status']='sellout';
				unset($_res['quan_receive']);
			}			
		}
		if($_res['volume']==''){			// 为空代表 挂了
			$_res['status']='sellout';
			unset($_res['volume']);
		}
		$item->where(array('num_iid'=>$res[$i]['num_iid']))->save($_res);
	}
}

if($j<$perCount )
	F('refresh_count',NULL);
else
	F('refresh_count',$end_pos );		//	实际更新个数
